<template>
  <div class="search-page">
    <!-- 页面头部 -->
    <div
      class="page-header bg-white dark:bg-gray-800 shadow-sm"
      :class="{ scrolled: isHeaderSticky }"
    >
      <!-- 面包屑导航 -->
      <div
        class="container mx-auto px-4 py-3 border-b border-gray-200 dark:border-gray-700"
      >
        <Breadcrumb
          :items="[{ path: '/', title: '首页' }, { title: '搜索结果' }]"
        />
      </div>

      <div class="container mx-auto px-4 py-5">
        <div
          class="flex flex-col md:flex-row md:items-center md:justify-between"
        >
          <div class="mb-4 md:mb-0">
            <h1
              class="text-2xl font-bold text-gray-900 dark:text-white mb-2 flex items-center"
            >
              <icon-search class="mr-2 text-primary-500" />搜索结果
            </h1>
            <p
              class="text-gray-600 dark:text-gray-400"
              v-if="!isLoading && resultCount > 0"
            >
              为您找到
              <span
                class="text-primary-600 dark:text-primary-400 font-medium"
                >{{ resultCount }}</span
              >
              条相关内容
            </p>
            <p
              class="text-gray-600 dark:text-gray-400"
              v-else-if="!isLoading && resultCount === 0"
            >
              未找到与
              <span class="text-primary-600 dark:text-primary-400 font-medium"
                >"{{ searchQuery }}"</span
              >
              相关的内容
            </p>
            <p
              class="text-gray-600 dark:text-gray-400 flex items-center"
              v-else
            >
              <icon-loading class="mr-2 animate-spin" />正在搜索...
            </p>
          </div>

          <div class="search-bar-container w-full md:w-auto">
            <div class="search-bar flex items-center">
              <div class="relative w-full">
                <a-input
                  v-model="searchQuery"
                  :style="{ width: '100%' }"
                  allow-clear
                  placeholder="请输入关键词搜索"
                  @input="handleInputChange"
                  @press-enter="handleSearch"
                  @focus="handleSearchFocus"
                  @blur="handleSearchBlur"
                >
                  <template #prefix>
                    <icon-search />
                  </template>
                </a-input>

                <!-- 统一的搜索下拉窗口 -->
                <div
                  v-if="(isSearchFocused || isSuggestionHovered) && !isLoading"
                  class="search-dropdown-panel"
                  @mouseenter="isSuggestionHovered = true"
                  @mouseleave="isSuggestionHovered = false"
                >
                  <!-- 搜索联想结果 -->
                  <div
                    v-if="searchSuggestions.length > 0"
                    class="search-dropdown-section"
                  >
                    <div class="search-dropdown-header">
                      <h3 class="search-dropdown-title">搜索建议</h3>
                    </div>
                    <div class="search-dropdown-items">
                      <div
                        v-for="(item, index) in searchSuggestions"
                        :key="`suggestion-${index}`"
                        class="search-dropdown-item"
                        @click="applyHistorySearch(item)"
                      >
                        <icon-search class="search-dropdown-icon" />
                        <span>{{ item }}</span>
                      </div>
                    </div>
                  </div>

                  <!-- 搜索按钮 (当有查询文本时显示) -->
                  <div
                    v-if="searchQuery.trim()"
                    class="search-dropdown-section"
                  >
                    <a-button
                      type="primary"
                      size="small"
                      class="w-full"
                      @click="handleSearch"
                    >
                      <template #icon>
                        <icon-search />
                      </template>
                      搜索: {{ searchQuery }}
                    </a-button>
                  </div>

                  <!-- 最近搜索 -->
                  <div
                    v-if="recentSearches.length > 0"
                    class="search-dropdown-section"
                  >
                    <div class="search-dropdown-header">
                      <h3 class="search-dropdown-title">最近搜索</h3>
                      <a-button
                        type="text"
                        size="mini"
                        @click.stop="clearRecentSearches"
                      >
                        清空
                      </a-button>
                    </div>
                    <div class="search-dropdown-items">
                      <div
                        v-for="(item, index) in recentSearches.slice(0, 5)"
                        :key="`recent-${index}`"
                        class="search-dropdown-item"
                        @click="applyHistorySearch(item)"
                      >
                        <icon-clock-circle class="search-dropdown-icon" />
                        <span>{{ item }}</span>
                      </div>
                    </div>
                  </div>

                  <!-- 热门搜索 -->
                  <div class="search-dropdown-section">
                    <div class="search-dropdown-header">
                      <h3 class="search-dropdown-title">热门搜索</h3>
                    </div>
                    <div class="search-dropdown-tags">
                      <a-tag
                        v-for="(item, index) in hotSearches.slice(0, 8)"
                        :key="`hot-${index}`"
                        color="arcoblue"
                        checkable
                        class="search-dropdown-tag"
                        @click.stop="applyHistorySearch(item)"
                      >
                        <template #icon>
                          <icon-fire />
                        </template>
                        {{ item }}
                      </a-tag>
                    </div>
                  </div>
                </div>
              </div>

              <a-dropdown trigger="click" position="br" :popup-max-height="300">
                <a-button class="ml-2" type="outline">
                  <template #icon>
                    <icon-filter />
                  </template>
                  筛选
                </a-button>
                <template #content>
                  <a-doption-group title="搜索范围">
                    <a-radio-group v-model="searchScope" type="button">
                      <a-radio value="all">全部</a-radio>
                      <a-radio value="spots">景点</a-radio>
                      <a-radio value="guides">攻略</a-radio>
                      <a-radio value="articles">文章</a-radio>
                      <a-radio value="photography">摄影</a-radio>
                      <a-radio value="news">资讯</a-radio>
                    </a-radio-group>
                  </a-doption-group>
                  <a-doption-group title="排序方式">
                    <a-radio-group v-model="sortBy" type="button">
                      <a-radio value="relevance">相关度</a-radio>
                      <a-radio value="latest">最新</a-radio>
                      <a-radio value="popular">热门</a-radio>
                    </a-radio-group>
                  </a-doption-group>
                  <a-divider style="margin: 8px 0" />
                  <div class="flex justify-between px-3 py-2">
                    <a-button size="small" @click="resetFilters">重置</a-button>
                    <a-button size="small" type="primary" @click="applyFilters"
                      >确定</a-button
                    >
                  </div>
                </template>
              </a-dropdown>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索结果内容 -->
    <div class="container mx-auto px-4 py-6">
      <!-- 搜索结果为空时的提示 -->
      <div v-if="!isLoading && resultCount === 0" class="empty-result">
        <a-empty description="没有找到符合条件的内容" class="py-16">
          <template #image>
            <div class="empty-image-wrapper">
              <icon-search
                style="font-size: 54px; color: var(--color-text-3)"
              />
            </div>
          </template>
          <template #extra>
            <div class="empty-suggestions">
              <p class="mb-4 text-center text-gray-500 dark:text-gray-400">
                您可以尝试：
              </p>
              <ul
                class="text-gray-600 dark:text-gray-400 list-disc list-inside text-left"
              >
                <li>检查输入是否有误</li>
                <li>尝试其他关键词</li>
                <li>使用更常见的词语</li>
                <li>减少筛选条件</li>
              </ul>
            </div>
          </template>
        </a-empty>
      </div>

      <!-- 分类选项卡和视图控件 -->
      <div v-if="!isLoading && resultCount > 0" class="search-results-layout">
        <!-- 分类标签侧边栏 -->
        <div class="sidebar-container">
          <div class="sidebar-header">
            <h3 class="text-lg font-semibold text-gray-800 dark:text-gray-200">
              内容分类
            </h3>
            <p class="text-sm text-gray-500 dark:text-gray-400">
              选择感兴趣的内容类型
            </p>
          </div>

          <div class="tab-nav-container">
            <div class="tab-nav bg-white dark:bg-gray-800 flex md:flex-col">
              <div
                v-for="tab in tabs"
                :key="tab.key"
                class="tab-item cursor-pointer transition-all flex items-center gap-2 whitespace-nowrap px-5 py-4"
                :class="{
                  'active-tab': activeTab === tab.key,
                  'border-b-2 md:border-b-0 md:border-l-4':
                    activeTab === tab.key,
                  'border-primary-500': activeTab === tab.key,
                }"
                @click="activeTab = tab.key"
              >
                <div class="tab-icon-container">
                  <component
                    :is="tab.icon"
                    class="tab-icon text-lg"
                    :class="{ 'text-primary-500': activeTab === tab.key }"
                  />
                </div>
                <span
                  class="tab-text font-medium"
                  :class="{
                    'text-primary-500 font-semibold': activeTab === tab.key,
                  }"
                  >{{ tab.title }}</span
                >
                <a-badge
                  v-if="tab.count > 0"
                  :count="tab.count"
                  :dot="false"
                  class="custom-badge"
                />
              </div>
            </div>
          </div>

          <!-- 侧边栏附加信息区域 -->
          <div class="sidebar-extra">
            <div class="search-stats mb-4">
              <h4
                class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
              >
                搜索统计
              </h4>
              <div class="grid grid-cols-2 gap-2">
                <div
                  class="stat-item bg-gray-50 dark:bg-gray-700 p-3 rounded-lg"
                >
                  <div class="text-xs text-gray-500 dark:text-gray-400">
                    结果总数
                  </div>
                  <div class="text-lg font-semibold text-primary-500">
                    {{ resultCount }}
                  </div>
                </div>
                <div
                  class="stat-item bg-gray-50 dark:bg-gray-700 p-3 rounded-lg"
                >
                  <div class="text-xs text-gray-500 dark:text-gray-400">
                    搜索用时
                  </div>
                  <div class="text-lg font-semibold text-primary-500">
                    {{ searchTime }}s
                  </div>
                </div>
              </div>
            </div>

            <div class="related-searches">
              <h4
                class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
              >
                相关搜索
              </h4>
              <div class="flex flex-wrap gap-1">
                <a-tag
                  v-for="(term, i) in relatedTerms"
                  :key="i"
                  :color="
                    ['arcoblue', 'green', 'orange', 'purple', 'magenta'][i % 5]
                  "
                  size="small"
                  class="cursor-pointer hover:shadow-sm transition-all hover:scale-105"
                  @click="applyHistorySearch(term)"
                  >{{ term }}</a-tag
                >
              </div>
            </div>
          </div>
        </div>

        <!-- 结果显示控件和内容区域 -->
        <div class="result-controls-and-content">
          <div
            class="sticky-controls bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700"
          >
            <div class="p-4 flex flex-wrap justify-between items-center">
              <div class="view-mode-controls mb-2 md:mb-0 flex items-center">
                <span class="text-gray-600 dark:text-gray-400 text-sm mr-2"
                  >视图：</span
                >
                <div
                  class="view-toggle-buttons flex bg-gray-100 dark:bg-gray-700 p-1 rounded-lg"
                >
                  <button
                    class="view-toggle-btn p-2 rounded-md transition-all flex items-center gap-1.5 border-0 focus:outline-none"
                    :class="
                      viewMode === 'list'
                        ? 'bg-white dark:bg-gray-600 shadow-sm text-primary-500'
                        : 'text-gray-500 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600'
                    "
                    @click="viewMode = 'list'"
                  >
                    <i class="fas fa-list"></i>
                    <span class="text-sm">列表</span>
                  </button>
                  <button
                    class="view-toggle-btn p-2 rounded-md transition-all flex items-center gap-1.5 border-0 focus:outline-none"
                    :class="
                      viewMode === 'card'
                        ? 'bg-white dark:bg-gray-600 shadow-sm text-primary-500'
                        : 'text-gray-500 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600'
                    "
                    @click="viewMode = 'card'"
                  >
                    <i class="fas fa-th-large"></i>
                    <span class="text-sm">卡片</span>
                  </button>
                </div>
              </div>

              <div class="sort-controls flex items-center">
                <span class="text-gray-600 dark:text-gray-400 text-sm mr-2"
                  >排序：</span
                >
                <a-select
                  v-model="sortBy"
                  :style="{ width: '120px' }"
                  size="small"
                  @change="handleSearch"
                >
                  <a-option value="relevance">相关度</a-option>
                  <a-option value="latest">最新</a-option>
                  <a-option value="popular">热门</a-option>
                </a-select>
              </div>
            </div>
          </div>

          <!-- 结果展示区域 -->
          <div class="search-results-container bg-white dark:bg-gray-800 p-4">
            <!-- 列表视图 -->
            <transition name="fade" mode="out-in">
              <a-space
                v-if="viewMode === 'list'"
                direction="vertical"
                :size="16"
                fill
                key="list-view"
              >
                <template
                  v-for="(item, index) in getCurrentResults"
                  :key="`list-${index}`"
                >
                  <div
                    class="search-result-item hover:shadow-md transition-all duration-300 rounded-lg overflow-hidden relative"
                    @click="navigateToResult(item)"
                  >
                    <!-- 自定义列表展示，不再使用SearchResultItem组件 -->
                    <div class="list-item-wrapper">
                      <div class="list-item-image">
                        <img
                          :src="item.image"
                          :alt="item.title"
                          class="h-full w-full object-cover transition-transform duration-500 hover:scale-105"
                          @error="handleImageError($event)"
                        />
                        <div class="absolute top-2 left-2">
                          <a-tag
                            :color="getTypeColor(item.type)"
                            size="small"
                            class="list-item-tag"
                          >
                            {{ getTypeLabel(item.type) }}
                          </a-tag>
                        </div>
                      </div>

                      <div class="list-item-content">
                        <div class="list-item-header">
                          <h3 class="list-item-title">{{ item.title }}</h3>
                          <div class="list-item-meta">
                            <span v-if="item.rating" class="meta-rating">
                              <icon-star-fill class="text-yellow-400 mr-1" />
                              {{ item.rating }}
                            </span>
                            <span class="meta-views">
                              <icon-eye class="mr-1" />
                              {{ formatNumber(item.viewCount) }}
                            </span>
                            <span class="meta-time" v-if="item.createdAt">
                              <icon-clock-circle class="mr-1" />
                              {{ formatTime(item.createdAt) }}
                            </span>
                          </div>
                        </div>

                        <p class="list-item-description">
                          {{ item.description }}
                        </p>

                        <div class="list-item-footer">
                          <div class="list-item-tags">
                            <a-tag
                              v-for="(tag, i) in item.tags.slice(0, 5)"
                              :key="i"
                              size="small"
                              bordered
                              class="tag-item"
                            >
                              {{ tag }}
                            </a-tag>
                          </div>

                          <div class="list-item-actions">
                            <a-button
                              type="outline"
                              size="mini"
                              class="action-btn"
                            >
                              <template #icon><icon-arrow-right /></template>
                              查看详情
                            </a-button>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="item-hover-overlay"></div>
                  </div>
                </template>
              </a-space>

              <!-- 卡片视图 -->
              <div
                v-else
                class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4"
                key="card-view"
              >
                <div
                  v-for="(item, index) in getCurrentResults"
                  :key="`card-${index}`"
                  class="search-result-card rounded-lg overflow-hidden transform transition-all duration-300 hover:shadow-lg hover:-translate-y-1"
                  @click="navigateToResult(item)"
                >
                  <div class="card-image-wrapper relative">
                    <img
                      :src="item.image"
                      :alt="item.title"
                      class="w-full h-48 object-cover transition-transform duration-500 hover:scale-110"
                      @error="handleImageError($event)"
                    />
                    <div
                      class="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent pointer-events-none"
                    ></div>
                    <div class="absolute top-2 left-2">
                      <a-tag
                        :color="getTypeColor(item.type)"
                        size="small"
                        class="type-tag"
                      >
                        {{ getTypeLabel(item.type) }}
                      </a-tag>
                    </div>
                    <div
                      class="absolute bottom-0 left-0 right-0 p-3 text-white"
                    >
                      <h3 class="text-lg font-bold line-clamp-1 mb-1">
                        {{ item.title }}
                      </h3>
                      <div class="flex items-center text-xs text-white/80">
                        <span v-if="item.rating" class="flex items-center mr-3">
                          <icon-star-fill class="text-yellow-400 mr-1" />
                          {{ item.rating }}
                        </span>
                        <span class="flex items-center">
                          <icon-eye class="mr-1" />
                          {{ formatNumber(item.viewCount) }}
                        </span>
                      </div>
                    </div>
                  </div>
                  <div class="card-content bg-white dark:bg-gray-800 p-3">
                    <p
                      class="text-sm text-gray-600 dark:text-gray-300 line-clamp-2 mb-3"
                    >
                      {{ item.description }}
                    </p>
                    <div class="tag-container flex flex-wrap gap-1">
                      <a-tag
                        v-for="(tag, i) in item.tags.slice(0, 3)"
                        :key="i"
                        size="small"
                        bordered
                      >
                        {{ tag }}
                      </a-tag>
                    </div>
                  </div>
                </div>
              </div>
            </transition>

            <!-- 空状态 -->
            <div
              v-if="getCurrentResults.length === 0 && !isLoading"
              class="text-center py-10"
            >
              <icon-inbox-alt
                style="font-size: 40px"
                class="text-gray-400 mb-2"
              />
              <p class="text-gray-500">此分类下暂无搜索结果</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div
        v-if="isLoading"
        class="loading-container flex justify-center items-center py-20"
      >
        <div class="loading-animation">
          <a-spin dot :size="40" tip="正在搜索，请稍候..." />
        </div>
      </div>

      <!-- 分页控件 -->
      <div
        v-if="!isLoading && resultCount > pageSize"
        class="pagination-container flex justify-center mt-8"
      >
        <a-pagination
          v-model:current="currentPage"
          v-model:page-size="pageSize"
          :total="resultCount"
          show-total
          show-page-size
          :page-size-options="[10, 20, 50]"
          @change="handlePageChange"
          class="custom-pagination"
        />
      </div>

      <!-- 将商品搜索提示移动到这里，并移除背景颜色 -->
      <div
        v-if="!isLoading && resultCount > 0"
        class="shop-search-tip mt-8 mb-5 border-t border-gray-200 dark:border-gray-700 pt-6 flex items-center justify-between"
      >
        <div class="flex items-center">
          <IconShoppingCart class="text-xl text-gray-500 mr-3" />
          <div>
            <p class="text-gray-700 dark:text-gray-200">
              想查找相关<strong>文创商品</strong>？
            </p>
            <p class="text-sm text-gray-500 dark:text-gray-400">
              本搜索不包含商品信息，请前往文创商城搜索。
            </p>
          </div>
        </div>
        <a-button type="outline" @click="navigateToShop" class="flex-shrink-0">
          <template #icon><icon-arrow-right /></template>
          前往文创商城
        </a-button>
      </div>

      <!-- 搜索历史和推荐 -->
      <div
        v-if="!isLoading && showRecommendations"
        class="recommendations-container mt-10"
      >
        <a-divider>搜索历史</a-divider>
        <div class="search-history mb-6">
          <div class="flex justify-between items-center mb-3">
            <span class="text-gray-600 dark:text-gray-400">您最近的搜索</span>
            <a-button
              type="text"
              size="small"
              status="danger"
              @click="clearSearchHistory"
            >
              清空历史
            </a-button>
          </div>
          <div class="flex flex-wrap gap-2">
            <a-tag
              v-for="(history, index) in searchHistory"
              :key="index"
              checkable
              class="history-tag cursor-pointer hover:scale-105 transition-transform"
              @click="applyHistorySearch(history)"
            >
              <template #icon>
                <icon-clock-circle />
              </template>
              {{ history }}
            </a-tag>
            <span
              v-if="searchHistory.length === 0"
              class="text-gray-500 dark:text-gray-400 text-sm"
            >
              暂无搜索历史
            </span>
          </div>
        </div>

        <a-divider>热门搜索</a-divider>
        <div class="hot-searches">
          <div class="flex flex-wrap gap-2">
            <a-tag
              v-for="(hot, index) in hotSearches"
              :key="index"
              color="arcoblue"
              checkable
              class="hot-tag cursor-pointer hover:scale-105 transition-transform"
              @click="applyHistorySearch(hot)"
            >
              <template #icon>
                <icon-fire />
              </template>
              {{ hot }}
            </a-tag>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, onBeforeUnmount } from "vue";
import { useRouter, useRoute } from "vue-router";
import { Message } from "@arco-design/web-vue";
import {
  IconSearch,
  IconFilter,
  IconLoading,
  IconRefresh,
  IconClose,
  IconClockCircle,
  IconFire,
  IconList,
  IconApps,
  IconEye,
  IconStarFill,
  IconLocation,
  IconUnorderedlist,
  IconInboxAlt,
  IconHome,
  IconCompass,
  IconBulb,
  IconShoppingCart,
  IconFile,
  IconArrowRight,
  IconCamera,
  IconNotification,
} from "@arco-design/web-vue/es/icon";
import Breadcrumb from "@/components/global/Breadcrumb.vue";
import {
  globalSearch,
  getHotSearches,
  getSearchSuggestions,
} from "@/api/search";

const router = useRouter();
const route = useRoute();

// 定义状态
const searchQuery = ref("");
const isLoading = ref(false);
const resultCount = ref(0);
const searchResults = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const searchScope = ref("all");
const sortBy = ref("relevance");
const activeTab = ref("all");
const showRecommendations = ref(true);
// 添加视图模式状态
const viewMode = ref("list"); // 默认为列表视图，可选值：'list' 或 'card'

// 定义标签
const tabs = computed(() => [
  {
    key: "all",
    title: "全部",
    icon: IconHome,
    count: resultCount.value,
  },
  {
    key: "spots",
    title: "景点",
    icon: IconCompass,
    count: spotResults.value.length,
  },
  {
    key: "guides",
    title: "攻略",
    icon: IconBulb,
    count: guideResults.value.length,
  },
  {
    key: "articles",
    title: "文章",
    icon: IconFile,
    count: articleResults.value.length,
  },
  {
    key: "photography",
    title: "摄影作品",
    icon: IconCamera,
    count: photographyResults.value.length,
  },
  {
    key: "news",
    title: "资讯",
    icon: IconNotification,
    count: newsResults.value.length,
  },
]);

// 搜索历史
const searchHistory = ref([]);
const MAX_HISTORY_ITEMS = 10;

// 热门搜索词
const hotSearches = ref([]);

// 添加搜索相关的状态变量
const searchSuggestions = ref([]);
const recentSearches = ref([]);
const debounceTimer = ref(null);

// 筛选出不同类型的结果
const spotResults = computed(() =>
  searchResults.value.filter((item) => item.type === "spot"),
);
const guideResults = computed(() =>
  searchResults.value.filter((item) => item.type === "guide"),
);
const articleResults = computed(() =>
  searchResults.value.filter((item) => item.type === "article"),
);
const photographyResults = computed(() =>
  searchResults.value.filter((item) => item.type === "photography"),
);
const newsResults = computed(() =>
  searchResults.value.filter((item) => item.type === "news"),
);

// 根据当前选中的标签获取结果
const getCurrentResults = computed(() => {
  switch (activeTab.value) {
    case "spots":
      return spotResults.value;
    case "guides":
      return guideResults.value;
    case "articles":
      return articleResults.value;
    case "photography":
      return photographyResults.value;
    case "news":
      return newsResults.value;
    default:
      return displayedResults.value;
  }
});

// 根据分页计算当前显示的结果
const displayedResults = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return searchResults.value.slice(start, end);
});

// 添加新的状态变量
const isSearchFocused = ref(false);
const isSuggestionHovered = ref(false);

// 在 script 部分添加新的数据
const searchTime = ref(0.32); // 搜索用时，可以根据实际情况计算

// 生成相关搜索词
const relatedTerms = computed(() => {
  if (!searchQuery.value) return [];

  // 基于当前搜索词和热搜生成相关词
  const terms = [];

  // 添加一些与当前搜索相关的词
  if (searchQuery.value.includes("贵港")) {
    terms.push("贵港旅游", "贵港历史", "贵港特产");
  } else if (searchQuery.value.includes("景点")) {
    terms.push("热门景点", "文化景点", "自然景点");
  } else if (searchQuery.value.includes("美食")) {
    terms.push("贵港小吃", "特色餐厅", "传统美食");
  } else {
    // 默认添加一些通用相关词
    terms.push(
      searchQuery.value + " 攻略",
      searchQuery.value + " 推荐",
      "热门" + searchQuery.value,
    );
  }

  // 从热搜中筛选相关词
  hotSearches.value.forEach((term) => {
    if (term.includes(searchQuery.value) || searchQuery.value.includes(term)) {
      terms.push(term);
    }
  });

  // 返回不重复的相关词，最多6个
  return [...new Set(terms)].slice(0, 6);
});

// 生命周期钩子
onMounted(async () => {
  // 从URL查询参数中获取搜索关键词
  if (route.query.q) {
    searchQuery.value = route.query.q;
    handleSearch();
  }

  // 加载热门搜索和搜索历史
  await Promise.all([loadHotSearches(), loadSearchHistory()]);

  // 从本地存储加载最近搜索
  const storedSearches = localStorage.getItem("recentSearches");
  if (storedSearches) {
    try {
      recentSearches.value = JSON.parse(storedSearches);
    } catch (e) {
      console.error("解析最近搜索失败", e);
      recentSearches.value = [];
    }
  }

  // 添加滚动监听
  window.addEventListener("scroll", handleScroll);

  // 添加窗口大小改变监听
  window.addEventListener("resize", updateSidebarPosition);
});

// 在组件销毁前移除滚动监听
onBeforeUnmount(() => {
  window.removeEventListener("scroll", handleScroll);
  window.removeEventListener("resize", updateSidebarPosition);
});

// 处理页面滚动
const isHeaderSticky = ref(false);
const lastScrollY = ref(0);
const scrollDirection = ref("none"); // 'up' 或 'down'

const handleScroll = () => {
  const currentScrollY = window.scrollY;

  // 判断滚动方向
  if (currentScrollY > lastScrollY.value) {
    scrollDirection.value = "down";
  } else if (currentScrollY < lastScrollY.value) {
    scrollDirection.value = "up";
  }

  // 更新上次滚动位置
  lastScrollY.value = currentScrollY;

  // 仅在桌面端更新侧边栏位置
  if (window.innerWidth >= 768) {
    updateSidebarPosition();
  }
};

// 添加一个新方法强制更新侧边栏位置
const updateSidebarPosition = () => {
  // 使用setTimeout来确保在下一个渲染周期执行
  setTimeout(() => {
    const sidebar = document.querySelector(".sidebar-container");
    if (sidebar) {
      // 强制重新计算样式
      sidebar.style.position = "";
      sidebar.offsetHeight; // 触发重排
      sidebar.style.position = "sticky";
    }
  }, 0);
};

// 计算侧边栏顶部位置
const sidebarTopOffset = computed(() => {
  return "20px"; // 固定值，因为头部不再固定
});

// 监听路由变化
watch(
  () => route.query.q,
  (newQuery) => {
    if (newQuery && newQuery !== searchQuery.value) {
      searchQuery.value = newQuery;
      handleSearch();
    }
  },
);

// 加载热门搜索
const loadHotSearches = async () => {
  try {
    const response = await getHotSearches();
    
    // 修正：检查response.data而不是response
    if (response && response.data && Array.isArray(response.data) && response.data.length > 0) {
      hotSearches.value = response.data;
    } else {
      // 使用默认数据
      hotSearches.value = [
        "贵港博物馆",
        "黄姚古镇",
        "文创纪念品",
        "美食推荐",
        "亲子活动",
        "特色民宿",
        "桂剧表演",
        "宝镜塔",
        "西津古渡",
        "石硖龙母祖庙",
      ];
    }
  } catch (error) {
    console.error("获取热门搜索失败", error);
    // 如果API调用失败，使用默认值
    hotSearches.value = [
      "贵港博物馆",
      "黄姚古镇",
      "文创纪念品",
      "美食推荐",
      "亲子活动",
      "特色民宿",
      "桂剧表演",
      "宝镜塔",
      "西津古渡",
      "石硖龙母祖庙",
    ];
  }
};

// 加载搜索历史 (使用本地存储)
const loadSearchHistory = () => {
  try {
    const history = localStorage.getItem("searchHistory");
    if (history) {
      searchHistory.value = JSON.parse(history);
    } else {
      searchHistory.value = [];
    }
  } catch (e) {
    console.error("解析搜索历史失败", e);
    searchHistory.value = [];
  }
};

// 处理输入变化的防抖函数
const handleInputChange = (value) => {
  if (debounceTimer.value) {
    clearTimeout(debounceTimer.value);
  }

  debounceTimer.value = setTimeout(async () => {
    if (value && value.trim().length >= 2) {
      try {
        // 调用搜索建议API
        const response = await getSearchSuggestions(value);
        
        // 修正：检查response.data而不是response
        if (response && response.data && Array.isArray(response.data) && response.data.length > 0) {
          searchSuggestions.value = response.data.slice(0, 10);
        } else {
          // 生成本地建议
          searchSuggestions.value = generateLocalSuggestions(value);
        }
      } catch (error) {
        console.error("获取搜索建议失败", error);
        // 生成基于本地数据的搜索建议
        searchSuggestions.value = generateLocalSuggestions(value);
      }
    } else {
      searchSuggestions.value = [];
    }
  }, 300); // 300ms 延迟，减少请求频率
};

// 生成本地搜索建议（API调用失败时的备选方案）
const generateLocalSuggestions = (keyword) => {
  if (!keyword || keyword.trim().length < 2) return [];

  const allTerms = [
    ...hotSearches.value,
    ...recentSearches.value,
    "贵港市博物馆",
    "黄姚古镇旅游",
    "贵港美食攻略",
    "贵港特产推荐",
    "贵港历史文化",
    "贵港一日游",
    "贵港周边游",
    "贵港住宿推荐",
    "贵港交通指南",
    "贵港购物攻略",
  ];

  // 过滤出匹配的建议
  return [...new Set(allTerms)]
    .filter((term) => term.toLowerCase().includes(keyword.toLowerCase()))
    .slice(0, 10);
};

// 清除最近搜索
const clearRecentSearches = () => {
  recentSearches.value = [];
  localStorage.removeItem("recentSearches");
  Message.success("已清空最近搜索");
};

// 搜索处理
const handleSearch = async () => {
  if (!searchQuery.value.trim()) {
    Message.warning("请输入搜索关键词");
    return;
  }

  try {
    isLoading.value = true;
    showRecommendations.value = false;

    // 记录到最近搜索
    const trimmedQuery = searchQuery.value.trim();
    // 如果已经存在，先移除再添加到开头
    recentSearches.value = recentSearches.value.filter(
      (item) => item !== trimmedQuery,
    );
    recentSearches.value.unshift(trimmedQuery);
    // 限制最近搜索的数量
    if (recentSearches.value.length > 10) {
      recentSearches.value = recentSearches.value.slice(0, 10);
    }
    // 保存到本地存储
    localStorage.setItem(
      "recentSearches",
      JSON.stringify(recentSearches.value),
    );

    // 添加到搜索历史（本地存储）
    addToSearchHistory(trimmedQuery);

    // 更新URL，无需刷新页面
    router.push({
      path: "/search",
      query: { ...route.query, q: searchQuery.value },
    });

    // 清空搜索建议
    searchSuggestions.value = [];

    // 设置搜索开始时间
    const startTime = Date.now();

    // 调用搜索API (不需要分页参数)
    const response = await globalSearch({
      keyword: searchQuery.value,
      scope: searchScope.value,
      sortBy: sortBy.value,
    });

    // 计算搜索用时
    searchTime.value = ((Date.now() - startTime) / 1000).toFixed(2);

    // 处理响应数据 - 修正：检查response.data而不是response
    if (response && response.data && response.data.items && response.data.items.length > 0) {
      // 有后端数据时使用后端数据
      searchResults.value = response.data.items;
      resultCount.value = response.data.total || response.data.items.length;
    } else {
      // 使用测试数据
      const mockResults = generateMockResults(searchQuery.value);
      searchResults.value = mockResults;
      resultCount.value = mockResults.length;
    }

    // 重置分页
    currentPage.value = 1;
  } catch (error) {
    console.error("搜索失败", error);
    
    // 计算搜索用时，即使使用测试数据
    searchTime.value = 0.32;
    
    // 使用测试数据
    const mockResults = generateMockResults(searchQuery.value);
    searchResults.value = mockResults;
    resultCount.value = mockResults.length;
  } finally {
    isLoading.value = false;
  }
};

// 重置筛选条件
const resetFilters = () => {
  searchScope.value = "all";
  sortBy.value = "relevance";
};

// 应用筛选条件
const applyFilters = () => {
  handleSearch();
  Message.success("已应用筛选条件");
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  // 本地分页，不需要调用API
  window.scrollTo({ top: 0, behavior: "smooth" });
};

// 跳转到搜索结果详情页
const navigateToResult = (item) => {
  let path;

  switch (item.type) {
    case "spot":
      path = `/spots/${item.id}`; // 景点详情页
      break;
    case "guide":
      path = `/tour-guide/${item.id}`; // 导游详情页
      break;
    case "travel_guide":
    case "travel-guide":
    case "travelguide":
      path = `/guides/${item.id}`; // 旅游攻略详情页
      break;
    case "article":
      path = `/articles/${item.id}`; // 文章详情页
      break;
    case "photography":
      path = `/photography/${item.id}`; // 摄影作品详情页
      break;
    case "news":
      path = `/news/detail/${item.id}`; // 资讯详情页
      break;
    default:
      console.warn("未知的结果类型:", item.type);

      // 对于商品类型，重定向到文创商城并打开搜索
      if (item.type === "product") {
        path = `/shop?q=${encodeURIComponent(searchQuery.value)}`;
        Message.info("商品搜索已转到文创商城");
      } else {
        return;
      }
  }

  // 记录点击事件
  recordResultClick(item.id, item.type);

  // 跳转到对应页面
  router.push(path);
};

// 记录结果点击 (可选的分析功能)
const recordResultClick = (itemId, itemType) => {
  try {
    // 可以在这里调用API记录点击行为，用于搜索结果优化
    console.log(`用户点击了搜索结果: ${itemType} - ${itemId}`);
    // 未来可以实现API调用
    // await recordSearchResultClick({ itemId, itemType, keyword: searchQuery.value });
  } catch (error) {
    console.error("记录搜索结果点击失败", error);
  }
};

// 获取类型颜色 (用于卡片视图)
const getTypeColor = (type) => {
  switch (type) {
    case "spot":
      return "blue";
    case "guide":
      return "green";
    case "travel_guide":
    case "travel-guide":
    case "travelguide":
      return "cyan";
    case "article":
      return "orange";
    case "photography":
      return "purple";
    case "news":
      return "magenta";
    default:
      return "gray";
  }
};

// 获取类型标签文字 (用于卡片视图)
const getTypeLabel = (type) => {
  switch (type) {
    case "spot":
      return "景点";
    case "guide":
      return "导游";
    case "travel_guide":
    case "travel-guide":
    case "travelguide":
      return "攻略";
    case "article":
      return "文章";
    case "photography":
      return "摄影作品";
    case "news":
      return "资讯";
    default:
      return "其他";
  }
};

// 格式化数字 (用于卡片视图)
const formatNumber = (num) => {
  if (!num && num !== 0) return "";

  if (num < 1000) return num.toString();
  if (num < 10000) return (num / 1000).toFixed(1) + "K";
  return (num / 10000).toFixed(1) + "万";
};

// 添加到搜索历史 (使用本地存储)
const addToSearchHistory = (query) => {
  if (!query || !query.trim()) return;

  const trimmedQuery = query.trim();

  // 移除已存在的相同查询
  searchHistory.value = searchHistory.value.filter(
    (item) => item !== trimmedQuery,
  );
  
  // 添加到开头
  searchHistory.value.unshift(trimmedQuery);
  
  // 限制历史记录数量
  if (searchHistory.value.length > MAX_HISTORY_ITEMS) {
    searchHistory.value = searchHistory.value.slice(0, MAX_HISTORY_ITEMS);
  }

  // 保存到本地存储
  localStorage.setItem("searchHistory", JSON.stringify(searchHistory.value));
};

// 清空搜索历史 (使用本地存储)
const clearSearchHistory = () => {
  searchHistory.value = [];
  localStorage.removeItem("searchHistory");
  Message.success("已清空搜索历史");
};

// 应用历史搜索
const applyHistorySearch = (query) => {
  searchQuery.value = query;
  handleSearch();
};

// 更新模拟生成数据逻辑，确保生成的数据更加符合实际情况
const generateMockResults = (query) => {
  // 示例数据，实际应该从API获取
  // 调整各类型的权重，文章和摄影作品比例更高
  const typeWeights = {
    spot: 0.2,
    guide: 0.2,
    article: 0.25,
    photography: 0.25,
    news: 0.1,
  };

  const results = [];

  // 生成20条模拟数据
  for (let i = 1; i <= 20; i++) {
    // 根据权重随机选择类型
    const randomValue = Math.random();
    let accWeight = 0;
    let type = "article"; // 默认类型

    for (const [t, weight] of Object.entries(typeWeights)) {
      accWeight += weight;
      if (randomValue <= accWeight) {
        type = t;
        break;
      }
    }

    let title, description, image, rating, tags;

    switch (type) {
      case "spot":
        title = `${query}相关景点 ${i}`;
        description = `这是一个与"${query}"相关的著名景点，位于贵港市区，拥有丰富的历史文化底蕴...`;
        image = `/images/spots/spot${(i % 5) + 1}.jpg`;
        rating = (3 + Math.random() * 2).toFixed(1);
        tags = ["景点", "文化", "热门"];
        break;
      case "guide":
        title = `${query}导游 ${i}`;
        description = `专业持证导游，擅长${query}相关路线讲解，为您提供贴心导游服务...`;
        image = `/images/guides/guide${(i % 5) + 1}.jpg`;
        rating = (3 + Math.random() * 2).toFixed(1);
        tags = ["导游", "专业", "持证"];
        break;
      case "travel_guide":
      case "travel-guide":
      case "travelguide":
        title = `${query}旅游攻略 ${i}`;
        description = `关于"${query}"的详细旅游攻略，包含交通、住宿、美食等实用信息...`;
        image = `/images/guides/guide${(i % 5) + 1}.jpg`;
        rating = (3 + Math.random() * 2).toFixed(1);
        tags = ["攻略", "实用", "精选"];
        break;
      case "article":
        title = `${query}相关文章 ${i}`;
        description = `与"${query}"相关的精彩文章，深度解析贵港文化旅游特色与魅力...`;
        image = `/images/articles/article${(i % 5) + 1}.jpg`;
        rating = null;
        tags = ["文章", "深度", "推荐阅读"];
        break;
      case "photography":
        title = `${query}的绝美瞬间 ${i}`;
        description = `摄影师捕捉的贵港"${query}"绝美景色，展现自然与人文的和谐之美...`;
        image = `/images/photography/photo${(i % 5) + 1}.jpg`;
        rating = (4 + Math.random()).toFixed(1);
        tags = ["摄影", "风光", "艺术"];
        break;
      case "news":
        title = `关于${query}的最新资讯 ${i}`;
        description = `最新"${query}"相关新闻报道，了解贵港文化旅游最新动态...`;
        image = `/images/news/news${(i % 5) + 1}.jpg`;
        rating = null;
        tags = ["资讯", "最新", "热点"];
        break;
    }

    results.push({
      id: i,
      type,
      title,
      description,
      image,
      rating,
      tags,
      createdAt: new Date(
        Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000,
      ).toISOString(),
      viewCount: Math.floor(Math.random() * 10000),
    });
  }

  // 根据搜索范围筛选
  if (searchScope.value !== "all") {
    return results.filter((item) => item.type === searchScope.value);
  }

  // 根据排序方式排序
  if (sortBy.value === "latest") {
    return results.sort(
      (a, b) => new Date(b.createdAt) - new Date(a.createdAt),
    );
  } else if (sortBy.value === "popular") {
    return results.sort((a, b) => b.viewCount - a.viewCount);
  }

  return results;
};

// 处理搜索框获取焦点
const handleSearchFocus = () => {
  isSearchFocused.value = true;
};

// 处理搜索框失去焦点
const handleSearchBlur = () => {
  // 延迟失去焦点处理，防止点击建议项时下拉框已经消失
  setTimeout(() => {
    if (!isSuggestionHovered.value) {
      isSearchFocused.value = false;
    }
  }, 200);
};

// 图片加载失败处理
const handleImageError = (event) => {
  // 使用内联SVG作为默认图片，确保始终有效
  event.target.src =
    "data:image/svg+xml;charset=UTF-8," +
    encodeURIComponent(
      '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"><rect width="200" height="200" fill="#f1f5f9"/><text x="50%" y="50%" font-family="Arial, sans-serif" font-size="14" text-anchor="middle" fill="#94a3b8" dy=".3em">暂无图片</text></svg>',
    );
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return "";

  const date = new Date(timestamp);
  const now = new Date();
  const diff = now - date;

  // 小于一天显示几小时前
  if (diff < 86400000) {
    const hours = Math.floor(diff / 3600000);
    return hours <= 0 ? "刚刚" : `${hours}小时前`;
  }

  // 小于7天显示几天前
  if (diff < 604800000) {
    const days = Math.floor(diff / 86400000);
    return `${days}天前`;
  }

  // 否则显示具体日期
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
};

// 添加前往文创商城的方法
const navigateToShop = () => {
  router.push({
    path: "/shop",
    query: searchQuery.value ? { q: searchQuery.value } : {},
  });
  Message.info("已为您跳转至文创商城");
};

// 在 <script> 中添加 head 标签引入 Font Awesome
const fontAwesomeLink = document.createElement("link");
fontAwesomeLink.rel = "stylesheet";
fontAwesomeLink.href =
  "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css";
document.head.appendChild(fontAwesomeLink);
</script>

<style lang="scss" scoped>
.search-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .page-header {
    box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;

    &.scrolled {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      background-color: rgba(255, 255, 255, 0.98);
      backdrop-filter: blur(10px);

      .dark & {
        background-color: rgba(31, 41, 55, 0.98);
      }
    }
  }

  .search-bar-container {
    @apply mb-4 md:mb-0;

    .search-bar {
      :deep(.arco-input-wrapper) {
        border-radius: 8px;
        border: 1px solid var(--color-neutral-3);
        transition: all 0.2s cubic-bezier(0.34, 0.69, 0.1, 1);

        &:hover,
        &:focus-within {
          border-color: rgb(var(--primary-6));
          box-shadow: 0 0 0 2px rgba(var(--primary-6), 0.2);
        }

        .arco-input-prefix {
          margin-right: 8px;

          .arco-icon {
            color: var(--color-text-3);
          }
        }
      }

      .search-dropdown-panel {
        @apply absolute top-full left-0 right-0 mt-1 bg-white dark:bg-gray-800 rounded-lg shadow-lg z-50 p-3;
        max-height: 400px;
        overflow-y: auto;
        border: 1px solid var(--color-neutral-3);

        .search-dropdown-section {
          @apply mb-3 last:mb-0;

          .search-dropdown-header {
            @apply flex justify-between items-center mb-2;

            .search-dropdown-title {
              @apply text-sm font-medium text-gray-600 dark:text-gray-400;
            }
          }

          .search-dropdown-items {
            @apply space-y-1;

            .search-dropdown-item {
              @apply flex items-center px-3 py-2 rounded-md text-gray-700 dark:text-gray-300 
                     hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer transition-colors;

              .search-dropdown-icon {
                @apply mr-2 text-gray-500 dark:text-gray-400;
              }
            }
          }

          .search-dropdown-tags {
            @apply flex flex-wrap gap-2;

            .search-dropdown-tag {
              @apply transition-transform duration-200 cursor-pointer;

              &:hover {
                @apply transform scale-105;
              }

              .arco-icon {
                margin-right: 4px;
              }
            }
          }
        }
      }
    }
  }

  .search-tabs-container {
    @apply shadow-lg;

    .tab-nav-container {
      @apply bg-white dark:bg-gray-800;

      .tab-nav {
        @apply py-1 md:py-2;

        .tab-item {
          @apply relative py-3 px-4 md:py-4 md:px-5 transition-all duration-200 flex items-center gap-2;

          &.active-tab {
            @apply bg-primary-50 dark:bg-primary-900/20;

            @media (min-width: 768px) {
              @apply border-l-4 border-l-primary-500;
            }

            @media (max-width: 767px) {
              @apply border-b-2 border-b-primary-500;
            }
          }

          &:hover:not(.active-tab) {
            @apply bg-gray-50 dark:bg-gray-700/50;
          }

          .tab-icon-container {
            @apply flex items-center justify-center w-8 h-8 rounded-full bg-gray-100 dark:bg-gray-700/70 transition-all duration-200;

            .tab-icon {
              @apply transition-all duration-200;
            }

            .active-tab & {
              @apply bg-primary-100 dark:bg-primary-900/50 text-primary-500;
              transform: scale(1.1);
            }
          }

          .tab-text {
            @apply transition-all duration-200;

            .active-tab & {
              @apply text-primary-500 font-semibold;
            }
          }

          .custom-badge {
            @apply transition-all duration-200;

            :deep(.arco-badge-number) {
              @apply text-xs px-1.5 min-w-[20px] h-5 leading-5 font-medium;
              transition: all 0.2s ease;
            }

            .active-tab & {
              transform: scale(1.1);
            }
          }
        }
      }
    }
  }

  .view-toggle-buttons {
    .view-toggle-btn {
      min-width: 80px;
      border: none !important;
      outline: none !important;

      &:first-child {
        margin-right: 4px;
      }

      &:focus {
        box-shadow: none;
      }
    }
  }

  .search-results-container {
    min-height: 400px;
  }

  .empty-result {
    @apply bg-white dark:bg-gray-800 rounded-lg shadow-md p-6;

    .empty-image-wrapper {
      @apply flex justify-center items-center h-32 w-32 mx-auto rounded-full bg-gray-100 dark:bg-gray-700 mb-6;
    }

    .empty-suggestions {
      @apply max-w-md mx-auto text-sm;
    }
  }

  .loading-animation {
    @apply animate-pulse bg-white dark:bg-gray-800 rounded-lg shadow-md p-10;
  }

  .item-hover-overlay {
    @apply absolute inset-0 bg-primary-500/0 transition-all duration-300 pointer-events-none;

    .search-result-item:hover & {
      @apply bg-primary-500/5;
    }
  }

  .search-result-card {
    @apply bg-white dark:bg-gray-800 shadow-sm cursor-pointer;
    height: 360px; /* 固定卡片高度 */
    display: flex;
    flex-direction: column;

    .card-image-wrapper {
      @apply relative overflow-hidden;
      height: 200px; /* 固定图片容器高度 */

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .card-content {
      @apply p-3 flex-1;
      display: flex;
      flex-direction: column;

      p {
        @apply mb-3;
      }

      .tag-container {
        margin-top: auto;
      }
    }

    .type-tag {
      font-weight: 500;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15);
    }
  }

  .pagination-container {
    :deep(.arco-pagination) {
      @apply py-4;

      .arco-pagination-item-active {
        @apply font-bold;
      }
    }
  }

  .recommendations-container {
    @apply bg-white dark:bg-gray-800 rounded-lg shadow-md p-6;

    :deep(.arco-divider) {
      margin: 16px 0;
    }

    :deep(.arco-divider-text) {
      @apply text-gray-500 dark:text-gray-400 text-sm;
    }

    .search-history,
    .hot-searches {
      @apply mb-4;
    }

    .history-tag,
    .hot-tag {
      @apply hover:shadow-md;
    }
  }

  .custom-view-toggle {
    :deep(.arco-radio-button) {
      @apply rounded-md overflow-hidden;

      &:first-child {
        @apply rounded-l-md;
      }

      &:last-child {
        @apply rounded-r-md;
      }
    }
  }

  .custom-pagination {
    :deep(.arco-pagination-item) {
      @apply rounded-md;
    }
  }

  // 淡入淡出动画
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.3s ease;
  }

  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
  }

  // 列表视图样式
  .search-result-item {
    @apply cursor-pointer bg-white dark:bg-gray-800;

    .list-item-wrapper {
      @apply flex flex-col sm:flex-row;

      .list-item-image {
        @apply relative overflow-hidden;
        height: 180px;
        flex: 0 0 auto;

        @media (min-width: 640px) {
          width: 240px;
          height: 100%;
        }

        img {
          @apply transition-transform duration-500;
        }

        .search-result-item:hover & img {
          @apply transform scale-105;
        }

        .list-item-tag {
          font-weight: 500;
          box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15);
        }
      }

      .list-item-content {
        @apply p-4 flex-1 flex flex-col;

        .list-item-header {
          @apply mb-2;

          .list-item-title {
            @apply text-lg font-bold text-gray-900 dark:text-white mb-2 line-clamp-1;
          }

          .list-item-meta {
            @apply flex flex-wrap items-center text-sm text-gray-500 dark:text-gray-400 gap-4;

            .meta-rating,
            .meta-views,
            .meta-time {
              @apply flex items-center;
            }
          }
        }

        .list-item-description {
          @apply text-sm text-gray-600 dark:text-gray-300 line-clamp-2 mb-4 flex-grow;
        }

        .list-item-footer {
          @apply flex justify-between items-center mt-auto;

          .list-item-tags {
            @apply flex flex-wrap gap-1 max-w-[75%];

            .tag-item {
              @apply transition-all duration-200;

              &:hover {
                @apply transform scale-105;
              }
            }
          }

          .list-item-actions {
            .action-btn {
              @apply text-xs text-primary-500 hover:text-primary-600 hover:bg-primary-50 transition-colors;
            }
          }
        }
      }
    }

    &:hover {
      @apply shadow-md;

      .action-btn {
        @apply bg-primary-50 dark:bg-primary-900/20;
      }
    }
  }

  // 更新搜索结果布局样式
  .search-results-layout {
    @apply mb-5 mt-4;
    display: grid;
    gap: 1rem;

    @media (min-width: 768px) {
      grid-template-columns: 16rem 1fr;
      align-items: start;
    }

    // 侧边栏容器
    .sidebar-container {
      @apply bg-white dark:bg-gray-800 rounded-lg shadow-sm;

      @media (min-width: 768px) {
        position: sticky;
        top: 80px; // 调整顶部间距，考虑顶部导航栏高度
        height: calc(100vh - 100px); // 相应调整高度
        overflow-y: auto;

        // 优化滚动条样式
        &::-webkit-scrollbar {
          width: 4px;
        }

        &::-webkit-scrollbar-track {
          background: rgba(0, 0, 0, 0.05);
        }

        &::-webkit-scrollbar-thumb {
          background: rgba(0, 0, 0, 0.1);
          border-radius: 2px;
        }
      }

      .sidebar-header {
        @apply px-4 py-3 border-b border-gray-200 dark:border-gray-700;
        display: none;

        @media (min-width: 768px) {
          display: block;
        }
      }

      .tab-nav-container {
        @apply border-b md:border-b-0;

        .tab-nav {
          @apply overflow-x-auto md:overflow-visible;
          scrollbar-width: none;

          &::-webkit-scrollbar {
            display: none;
          }
        }
      }

      .sidebar-extra {
        @apply p-4 border-t border-gray-200 dark:border-gray-700;
        display: none;

        @media (min-width: 768px) {
          display: block;
        }
      }
    }

    // 结果区域
    .result-controls-and-content {
      @apply bg-white dark:bg-gray-800 rounded-lg shadow-sm;

      .sticky-controls {
        position: sticky;
        top: 0;
        z-index: 5;
        backdrop-filter: blur(5px);
      }
    }
  }
}
</style>
